<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

Class Tvshow extends MY_Controller {

    public function __construct() {
        parent::__construct();
        //$this->checkUser($this->session->userdata('user_id'));
        $this->data['controller'] = 'tvshow';
        $this->load->model('Mtvshow');
    }

    public function index() {
        if(in_array($this->session->userdata('id_mem'), array(null, '', '0')))
        {
            $this->createguest();
        }
        $name_ascii = $this->getParamUri(2, 0);
        $this->data['uriCurrent'] = base_url(uri_string());
        $this->data['data'] = $this->Mtvshow->getTvShow($name_ascii);
        $this->data['id_show'] = $this->getParamInt('id_show');

        $this->data['action'] = 'index';
        $this->load->view('template/layout', $this->data);
    }
    
    
     public function checkfb()
    {
        
        require_once PROJECT_PATH."/lib/fb/facebook.php"; //include facebook SDK
		$facebook = new Facebook(array('appId'  => $this->app_id,'secret' => $this->app_secret,  'return_url' => $return_url));
        $user_fb = $facebook->getUser();
        
        if(!in_array($this->getParamString('code'), array(null, '', '0')) && $this->session->userdata('loginFbAjax') != 1)
        {
            $this->session->set_userdata(array('loginFbAjax' => 1));
            redirect($this->session->userdata('url_current'));
        }
        
        if(in_array($user_fb, array(null, '', 0))){
            
            $login_url = $facebook->getLoginUrl( array('scope' => 'photo_upload') );
            $this->session->set_userdata(array('url_current' => $_SERVER['HTTP_REFERER']));
            die(json_encode((object)array('status' => 201, 'url' => $login_url)));
            
        }else{
            
            $user_id    = $this->getParamString('user_id');
            $cover      = $this->downloadImage($this->getParamString('cover'), $user_id);
            $data_question        = json_decode(str_replace('\"','"',$this->getParamString('data_questions')));
            $title_show = 'Chương trình: '.$this->getParamString('show_name');
            
            $name_images = $user_id.'.jpg';
            $paths = PROJECT_PATH.'/data/share/';
            $arr_exp = array('[removed]', '[removed');
            
            $exp = str_replace($arr_exp,'',$pic);
            $this->savefile($exp,$paths,$name_images);
            
            $SourceFile = $paths.$name_images;
            $DestinationFile = $cover;
            $cover = $cover;
			
            
            $font = PROJECT_PATH.'/public/fonts/UVFFuturaLT.ttf';
            $SourceFile = PROJECT_PATH.'/public/images/bg.jpg';
            $opacity_rend = PROJECT_PATH.'/public/images/opacity_rend.png';
            
            $DestinationFile = $cover; 
            $cover = $cover;
            $this->addcover($SourceFile, $cover, $DestinationFile, 0 , 0);
            $content = wordwrap($data_question->question." \n\n", 150, "\n");
            $WaterMarkText = $content;
            
            $box = @imagettfbbox(14, 0, $font, $WaterMarkText); 
            
            $width = abs($box[4] - $box[0]); 
            $height = abs($box[3] - $box[5]); 
            
            $this->watermarkImage($DestinationFile, $WaterMarkText, $DestinationFile, $font_size = 14, 10, 400, $font);
            
            $choice = (array)$data_question->choice;
            $i = 1;
            $content_choice = $content_choice2 = '';
            $count = sizeOf($choice);
            foreach($choice AS $el=>$le)
            {
                if($i > 4)
                {
                    /*if($i/4 == 1)
                    {
                        $this->addcover($DestinationFile, $opacity_rend, $DestinationFile, 450, $height + 400 + 10);
                    }*/
                     if($count > 4)
                     {
                        $content_choice  .= wordwrap("        Lựa chọn ".$i.": ".$choice['id_'.$i][0]."\n\n", 100, "\n");
                     }else{
                        $content_choice  .= "        Lựa chọn ".$i.": ".$choice['id_'.$i][0]."\n\n";
                     }
                     
                     $this->watermarkImage($DestinationFile, $content_choice, $DestinationFile, $font_size = 14, 450, $height + 400 + 30, $font);                 
                }else{
                    /*if($i == 1)
                    {
                        $this->addcover($DestinationFile, $opacity_rend, $DestinationFile, 450, $height + 400 + 10);
                    }*/
                    if($count > 4)
                     {
                        $content_choice2  .= wordwrap("        Lựa chọn ".$i.": ".$choice['id_'.$i][0]."\n\n", 100, "\n");
                     }else{
                        $content_choice2  .= "        Lựa chọn ".$i.": ".$choice['id_'.$i][0]."\n\n";
                     }
                    
                    $this->watermarkImage($DestinationFile, $content_choice2, $DestinationFile, $font_size = 14, 10, $height + 400 + 30, $font);
                }
                $i++;
            }
            $this->watermarkImage($DestinationFile, $title_show, $DestinationFile, $font_size = 22, 10, 360, $font);
			
            die(json_encode((object)array('status' => 200, 'url' => null)));
        }
        
    }
    
    
    private function downloadImage($cover, $user)
    {
        $render = PROJECT_PATH.'/data/share/cover/cover-'.$user.'.jpg';
        //die($cover);
        copy($cover, $render);
        return $render;
    }
    
    
    public function sharefb()
    {
        require_once PROJECT_PATH."/lib/fb/facebook.php"; //include facebook SDK
		 $config = array(
            'appId' => $this->app_id,
            'secret' => $this->app_secret,
            'fileUpload' => true,
            'cookie' => true
        );
        
        $facebook = new Facebook($config);
        $facebook->setFileUploadSupport(true);
        $user_fb = $facebook->getUser();
        
        $user_id    = $this->getParamString('user_id');
        $msg        = $this->getParamString('msg');
        $uri        = $this->getParamString('uri');
        $choice     = $this->getParamInt('choice');
       
        if($choice != 0)
        {
            $choice = "Tôi đã chọn đáp án: ".$choice.". Bạn sẽ chọn đáp án nào ?\n";
        }else{
            $choice = "\n";
        }
        
        try {
             $msg_ = $msg."\n\n Mình đang chơi chương trình này, mời bạn chơi cùng mình\n" .$choice ." Tham gia chương trình tại địa chỉ: ". $uri;
             $ret_obj = $facebook->api('/me/photos', 'POST',
                        array(
                               'source' =>  '@' .realpath(PROJECT_PATH.'\data\share\cover\cover-'.$user_id.'.jpg'),
                               'message' => $msg_,
                           )
             );
             die($ret_obj['id'].'--');
             if($ret_obj['id'])
            {
                die((object)array('status' => 200));
            }else{
                die((object)array('status' => 201));
            }
        } catch(FacebookApiException $e) {
            echo "<pre>";
            die(print_r($e));
          error_log($e->getType());
          error_log($e->getMessage()); 
        }   
    }


    public function ajaxplusflag0(){
		die($this->Mtvshow->ajaxplusflag0());
	}
}
